# tkinter实现二维码生成功能
from tkinter import *
from PIL import Image, ImageTk
from urllib import request


class Window(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        self.init_window()

    def init_window(self):
        self.master.title("二维码生成器 V0.0")
        self.pack(fill=BOTH, expand=1)
        self.createWidgets()

    def createWidgets(self):
        self.urlInput = Entry(self)
        self.urlInput.pack()
        self.Button = Button(self, text='生成', command=self.showImg)
        self.Button.pack()

    def showImg(self):
        str = self.urlInput.get() or 'http://wevsmy.cn'
        self.createQRcode(url=str)
        load = Image.open('image.jpg')  # 图片的相对路径
        render = ImageTk.PhotoImage(load)
        img = Label(self, image=render)
        img.image = render
        img.place(x=0, y=50)

    def createQRcode(self,url="http://wevsmy.cn"):
        # 生成二维码
        requestUrl="https://pan.baidu.com/share/qrcode?w=150&h=150&"
        requestUrl = requestUrl+"url={}".format(url)
        with request.urlopen(requestUrl) as f:
            data = f.read()
            with open("image.jpg",mode="wb") as f:
                f.write(data)


if __name__ == '__main__':
    root = Tk()
    root.geometry("150x200")
    app = Window(root)
    root.mainloop()